const express = require('express')

const staticRouter = express()
const { articleModel } = require('../model/articleSchema');
const handleTime = require('../utils/formatTime')

staticRouter.get('/', (req, res) => {
    res.render('./pages/home.html', {
        ...req.session.userInfo
    })
})

//注册静态页面路由
staticRouter.get('/register', (req, res) => {
    res.render('./pages/register.html')
})

//登陆
staticRouter.get('/login', (req, res) => {
    req.session.userInfo = null
    res.render('./pages/login.html')
})

//退出
staticRouter.get('/out', (req, res) => {
    req.session.userInfo = null
    res.redirect('/')
})

//用户信息页面
staticRouter.get('/user/:type', async(req, res) => {
    let publishArr = null
    let ratingArr = null

    if (!req.session.userInfo) {
        res.redirect('/')
        return
    }

    if (req.params.type == 'info') {
        publishArr = await articleModel.find({ userInfo: req.session.userInfo._id }, { content: 0 })
            .populate({
                path: 'ratings',
                select: 'date avatar',
                options: { limit: 1, sort: { _id: -1 } }
            })
            .populate({
                path: 'userInfo',
                select: 'avatar'
            }).sort({ '_id': -1 })

        ratingArr = await articleModel.find({ ratingUser: { $elemMatch: { $eq: req.session.userInfo._id } } }, { content: 0 })
            .populate({
                path: 'ratings',
                select: 'date avatar',
                options: { limit: 1, sort: { _id: -1 } }
            })
            .populate({
                path: 'userInfo',
                select: 'avatar'
            }).sort({ '_id': -1 })
    }

    res.render('./pages/user.html', {
        ...req.session.userInfo,
        type: req.params.type,
        publishArr,
        ratingArr,
        distanceTime: handleTime.distanceTime
    })
})


module.exports = staticRouter